package com.hairline.config;

import com.hairline.shiro.MallToken;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;

import java.util.ArrayList;
import java.util.Collection;

//注册它,也可以在 config里面手动注册
//用注解注册 的话如何传入 自定义的relams?
//分发 relam
public class ContralRealmAuthenticator extends ModularRealmAuthenticator {
    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
        this.assertRealmsConfigured();
        //给他改名
        Collection<Realm> originRealms = this.getRealms();

        //根据token 对realm处理 即需要token多携带一个信息
        //强转并获得信息
        MallToken token = (MallToken) authenticationToken;
        String type = token.getType();

        //自己建立的集合用于 之后选择的realm
        ArrayList<Realm> realms = new ArrayList<>();

        for (Realm originRealm : originRealms) {
            String name = originRealm.getName().toLowerCase();
            //将原本的realms获得名字,并且判断它是否是我们想要的realm,是的话就加入自己的list
            if (name.contains(type)) {
                realms.add(originRealm);
            }

        }

        return realms.size() == 1 ? this.doSingleRealmAuthentication((Realm) realms.iterator().next(), authenticationToken) : this.doMultiRealmAuthentication(realms, authenticationToken);

    }
}
